/** 主题类型 */
const _THEMES_ = ['', 'dark', 'colorless'] as const;
type Ttheme_index = TarrayIndexs<typeof _THEMES_['length']>;
type Ttheme_value = typeof _THEMES_[number];

interface _IK_ {
    theme: {
        /** 主题键 */
        key: string;
        /** 主题取值范围 */
        range: readonly string[];
        /**
         * 取当前主题
         */
        get(): Ttheme_value;
        /**
         * 切换到下一个主题
         */
        set(): void;
        /**
         * 切换到下一个主题
         * @param theme 主题
         */
        set(theme: undefined): void;
        /**
         * 切换到下一个主题
         * @param theme 主题
         */
        set(theme: null): void;
        /**
         * 切换到指定主题
         * @param theme 主题 K.theme.range数组索引值。超出索引值则取默认值0；
         */
        set(theme: Ttheme_index): void;
        /**
         * 切换到指定主题
         * @param theme 主题 K.theme.range数组中的值。不在定义中则取默认值第一项；
         */
        set(theme: Ttheme_value): void;
    };
}
{
    const next_theme = () => {
        let themeIdx = K.theme.range.indexOf(K.theme.get()) + 1;
        if (themeIdx >= K.theme.range.length) { themeIdx = 0; }
        K.theme.set(themeIdx as Ttheme_index);
    };
    K.theme = {
        key: 'data-theme',
        range: _THEMES_,
        get: () => {
            const theme = document.documentElement.getAttribute(K.theme.key);
            if (theme === null) { return (K.theme.range[0]) as Ttheme_value; }
            return (K.theme.range.indexOf(theme) < 0 ? K.theme.range[0] : theme) as Ttheme_value;
        },
        set: U.F.overloading('Plugin-theme-set',
            {
                types: [],
                fn: next_theme
            },
            {
                types: [[Etype.undefined, Etype.null]],
                fn: next_theme
            },
            {
                types: [Etype.number],
                fn: (theme: number) => {
                    let themeIdx = (theme >= 0 && theme < K.theme.range.length) ? theme : 0;;
                    document.documentElement.setAttribute(K.theme.key, K.theme.range[themeIdx]);
                }
            },
            {
                types: [Etype.string],
                fn: (theme: string) => {
                    theme = (K.theme.range.indexOf(theme as Ttheme_value) >= 0) ? theme : K.theme.range[0];
                    document.documentElement.setAttribute(K.theme.key, theme);
                }
            },
        )
    };
}

interface _CP_<T extends object> {
    /** 
    * 主题切换时控件处理方法
    * @param theme 主题
    */
    onThemeChange(theme: Ttheme_value): void;
}
{
    Object.defineProperty(_CP_.prototype, 'onThemeChange', {
        writable: false,
        configurable: false,
        enumerable: false,
        value: U.F.fn.void
    });
}

// 监听主题切换
{
    new MutationObserver((mutationsList, observer) => {
        for (const mutation of mutationsList) {
            if (mutation.type === 'attributes') {
                const theme = K.theme.get();
                if (theme) {// 非默认主题
                    if (!document.head.querySelector(`link#${theme}`)) {// 没有引入对应主题样式
                        const link = document.createElement('link');
                        link.id = theme;
                        link.rel = 'stylesheet';
                        link.href = `/plugins/theme-${theme}.css`;
                        document.head.appendChild(link);
                    }
                }
                // 触发控件关于主题的实现
                document.querySelectorAll(`.${_CP_.CLASSES.PLUGIN}`).forEach(ele => {
                    if (ele instanceof HTMLElement && ele.creator) {
                        ele.creator.onThemeChange(theme);
                    }
                });
            }
        }
    }).observe(document.documentElement, { attributes: true, attributeFilter: [K.theme.key] });
}

// 双击[Shift]切换主题
{
    let _last_action_time = 0;
    document.addEventListener('keydown', (event) => {
        if (event.key === 'Shift') {
            const now = Date.now();
            const diff = now - _last_action_time;
            _last_action_time = now;
            if (diff < 200 && diff > 100) { K.theme.set(); }
        }
    });
}
